package jsen.tool.ddd.adapter.event.demo;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import jsen.tool.ddd.adapter.event.Consumer;
import jsen.tool.ddd.adapter.event.DomainEvent;
import jsen.tool.ddd.adapter.event.IEventBus;
import jsen.tool.ddd.adapter.event.common.EventBus;

import java.util.concurrent.Executors;

/**
 * @author jsen
 * @date 2021/10/6
 */
public class EventBusTest {
    private static final IEventBus EVENT_BUS = new EventBus(Executors.newFixedThreadPool(6));

    public static void main(String[] args) {
        EVENT_BUS.register(new EchoSimpleConsumer());
        EVENT_BUS.register(new MqConsumer());
        testFire();
        testFireAsync();
        testFireParallel();
    }

    private static void testFire() {
        EVENT_BUS.fireEvent(new EchoDomainEvent("jsen"));
        System.out.println("succeed testFire");
    }

    private static void testFireAsync() {
        EVENT_BUS.fireEventAsync(new EchoDomainEvent("jsen"), e -> System.out.println("succeed testFireAsync"));
    }

    private static void testFireParallel() {
        EVENT_BUS.fireEventParallel(new EchoDomainEvent("jsen"), e -> System.out.println("succeed testFireParallel"));
    }

    private static class EchoDomainEvent implements DomainEvent {
        private final String name;

        public EchoDomainEvent(String name) {
            this.name = name;
        }

        @Override
        public int getVersion() {
            return 2;
        }

        @Override
        public long getOccurredOn() {
            return 3L;
        }

        @Override
        public String getId() {
            return "getId";
        }
    }

    private static class EchoSimpleConsumer implements Consumer<EchoDomainEvent> {
        @Override
        public void accept(EchoDomainEvent t) {
            System.out.println("echo " + t.name);
        }
    }

    private static class MqConsumer implements Consumer<DomainEvent> {
        @Override
        public void accept(DomainEvent t) {
            System.out.println("mq " + toJson(t));
        }

        @Override
        public boolean match(DomainEvent domainEvent) {
            return true;
        }
    }

    public static String toJson(Object object) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        return gson.toJson(object);
    }
}
